package com.itany.factory;

import com.itany.util.ParameterUtil;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/**
 * Author:石小俊
 * Date: 2022/11/3 16:37
 * 由于对象之间可能存在依赖关系
 * 被依赖的对象必须在之前进行配置
 */
public class ObjectFactory {

//    public static Object getObject(String key) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
//        if("user".equals(key)){
//            return Class.forName("com.itany.factory.User").newInstance();
//        } else if("emp".equals(key)){
//            return Class.forName("com.itany.factory.Emp").newInstance();
//        } else if("date".equals(key)){
//            return Class.forName("java.util.Date").newInstance();
//        }else{
//            return null;
//        }
//    }

    private static Map<String,Object> objs;

    static{
        objs = new HashMap<>();
        try {
            BufferedReader br = new BufferedReader(
                    new InputStreamReader(
                            ObjectFactory
                            .class
                            .getClassLoader()
                            .getResourceAsStream("beans.properties")));
            String line = null;
            while((line = br.readLine()) != null){
                if(!ParameterUtil.isNull(line)){
                    String[] arr = line.split("=");
                    String key = arr[0];
                    String value = arr[1];
                    objs.put(key,Class.forName(value).newInstance());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new ExceptionInInitializerError("ObjectFactory初始化失败");
        }
    }

    public static Object getObject(String key){
        Object obj = objs.get(key);
        if(null == obj){
            System.out.println("根据key:"+key+"在对应的配置文件中没有找到对应的配置");
            return null;
        }
        return obj;
    }

}
